package com.yun.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yun.blog.bean.LoginBean;
import com.yun.blog.bean.RegisterBean;
import com.yun.blog.bean.User;
import com.yun.blog.service.LoginService;
import com.yun.blog.service.UserService;
import com.yun.blog.utils.JwtUtils;
import com.yun.blog.utils.Md5;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;

/**
 * @author : simple
 * @title : LoginServiceImpl
 * @projectName : dantouBlog-back
 * @description : 登录接口
 * @email : yun_simple@163.com
 * @date : 2023/5/21下午8:35
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    UserService userService;


    @Override
    public HashMap<String, Object> login(LoginBean loginBean, HttpSession session) {
        // 判断验证码
        String captchaCode = (String) session.getAttribute("KAPTCHA_SESSION_KEY");
        if (loginBean.getCaptchaCode() == null || !loginBean.getCaptchaCode().equalsIgnoreCase(captchaCode)) {
            throw new RuntimeException("验证码错误！");
        }
        User user = userService.getOneByUsernameAndPassword(loginBean.getUsername(), Md5.md5(loginBean.getPassword()));
        if (user == null) {
            throw new RuntimeException("用户名或密码错误！");
        }
        if (user.getIsLock()) {
            throw new RuntimeException("账号已锁定，没有登录权限！");
        }
        // 更新最后登录时间
        userService.updateLastLoginTimeByUserId(user.getUserId());
        // 设置token
        String token = JwtUtils.getToken(user.getUserId(), user.getUserUsername(), user.getUserNickName());
        HashMap<String, Object> dateMap = new HashMap<>();
        dateMap.put("token", token);
        // 设置给前端传递的password字段为空
        user.setUserPassword("");
        dateMap.put("userInfo", user);
        // 验证码失效
        session.removeAttribute("KAPTCHA_SESSION_KEY");
        return dateMap;
    }

    @Override
    public boolean register(RegisterBean registerBean, HttpSession session) {
        // 判断验证码
        String captchaCode = (String) session.getAttribute("KAPTCHA_SESSION_KEY");
        if (registerBean.getCaptchaCode() == null || !registerBean.getCaptchaCode().equalsIgnoreCase(captchaCode)) {
            throw new RuntimeException("验证码不正确");
        }
        // 检查账号是否可用
        if (!checkUsernameCanUse(registerBean.getUsername(), 0)) {
            throw new RuntimeException("账号不可用!");
        }
        User user = new User();
        user.setUserNickName(registerBean.getNickName());
        user.setUserUsername(registerBean.getUsername());
        user.setUserPassword(Md5.md5(registerBean.getPassword()));
        user.setIsSuperuser(false);
        user.setIsLock(false);
        // 设置随机0-6 为默认头像 0-6.png
        Random random = new Random();
        user.setHeadImg("/src/assets/default/" + random.nextInt(7) + ".png");
        return userService.save(user);
    }

    public boolean checkUsernameCanUse(String username, Integer userId) {
        if (!StringUtils.hasText(username) || username.length() > 12) {
            return false;
        }
        QueryWrapper<User> query = Wrappers.query();
        query.eq("user_username", username);
        User one = userService.getOne(query);
        // 如果前端传递的id是null，就是新增，这种情况下，one==null表示用户名可用
        // 如果前端传递了id，查询的id==传递的id，表示在修改本账号的其他信息，
        // 如果查到的id ！= 传递的id，表示修改usrename但是被占用
        return one == null || one.getUserId().equals(userId);
    }


}
